package com.qf.juc.demo.readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁  ReentrantReadWriteLock
 */
public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {

        MyLock myLock = new MyLock();
        for (int i = 1; i <6 ; i++) {
            final int temp = i;
            new Thread(()->{
                myLock.wirte(temp);
            },String.valueOf(i)).start();
        }


        for (int i = 1; i <6 ; i++) {
            final int temp = i;
            new Thread(()->{
                myLock.read(temp);
            },String.valueOf(i)).start();
        }
    }





}


class MyLock{

    private Map<Object,Object> map = new HashMap<>();

    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void wirte(int i){
        readWriteLock.writeLock().lock();

        try{
            System.err.println(i+"：开始写入");
            map.put(i,i);
            System.err.println(i+"：写入成功");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }


    public void read(int i){
        readWriteLock.readLock().lock();

        try{
            System.out.println(i+"：开始读取");
            Object o = map.get(i);
            System.out.println(o+"：读取成功");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
    }
}
